'use strict';

angular.module('afasApp')
.filter('groupBy', ['$parse', '$filter', function ($parse, $filter) {
  return function (list, groupBy) {

    var filtered = [];
    var prevItem = null;
    var groupChanged = false;

    var newField = 'groupBy_CHANGED';

    list = $filter('orderBy')(list, groupBy);

    angular.forEach(list, function (item) {

      groupChanged = false;

      if (prevItem !== null) {

        // groupBy = angular.isArray(groupBy) ? groupBy : [groupBy];

        // for (var i = 0, len = groupBy.length; i < len; i++) {
        if ($parse(groupBy)(prevItem) !== $parse(groupBy)(item)) {
          groupChanged = true;
        }
        // }


      } else {
        groupChanged = true;
      }

      if (groupChanged) {
        item[newField] = true;
      } else {
        item[newField] = false;
      }

      filtered.push(item);
      prevItem = item;

    });

    return filtered;
  };
}]);